﻿// MIT License
// 开源地址：https://gitee.com/co1024/AbcMvc
// Copyright (c) 2021-2023 1024
// Abc.Mvc=Furion+EF+SqlSugar+Pear layui admin.


using Furion.DatabaseAccessor;
using System.Linq.Expressions;

namespace Abc.Utils;

/// <summary>
/// sqlsugar 缓存的仓储
/// 警告：小数据量的表才用，否则可能会造成意想不到的问题
/// </summary>
/// <typeparam name="TEntity"></typeparam>
public class SqlSugarCacheRepository<TEntity> : SqlSugarRepository<TEntity> where TEntity : class, new()
{

    public SqlSugarCacheRepository(ISqlSugarClient db = null, IServiceProvider serviceProvider = null) : base(db, serviceProvider)
    {
    }


    #region Cache
    /// <summary>
    /// 动态设置的方法，获取缓存数据的
    /// 因为如果此仓储
    /// </summary>
    private Func<List<TEntity>> RefreshMethod = null;

    /// <summary>
    /// 设置获取数据的方法
    /// </summary>
    /// <param name="func">委托方法</param>
    public void SetRefreshMethod(Func<List<TEntity>> refreshMethod)
    {
        RefreshMethod = refreshMethod;
    }
    /// <summary>
    /// 缓存数据
    /// </summary>
    public List<TEntity> CacheDatas => RefreshCache();

    /// <summary>
    /// 刷新缓存
    /// </summary>
    /// <returns></returns>
    public List<TEntity> RefreshCache()
    {
        return RefreshCacheAsync().GetAwaiter().GetResult();
    }

    /// <summary>
    /// 刷新缓存
    /// </summary>
    /// <returns></returns>
    public virtual async Task<List<TEntity>> RefreshCacheAsync()
    {
        //判断刷新方法是否为空
        if (RefreshMethod != null)
        {
            return RefreshMethod();
        }
        else
        {
            return await _db.Queryable<TEntity>().WithCache().ToListAsync();
        }
    }


    /// <summary>
    /// 获取全部集合
    /// </summary>
    /// <returns></returns>
    public List<TEntity> GetCacheList()
    {
        return RefreshCache();
    }
    /// <summary>
    /// 获取全部集合
    /// </summary>
    /// <returns></returns>
    public async Task<List<TEntity>> GetCacheListAsync()
    {
        return await RefreshCacheAsync();
    }
    #endregion Cache












}

//public class SqlSugarCacheRepository
//{
//    /// <summary>
//    /// 服务提供器
//    /// </summary>
//    private readonly IServiceProvider _serviceProvider;

//    /// <summary>
//    /// 构造函数
//    /// </summary>
//    /// <param name="serviceProvider">服务提供器</param>
//    public SqlSugarCacheRepository(
//        IServiceProvider serviceProvider)
//    {
//        _serviceProvider = serviceProvider;
//    }

//    /// <summary>
//    /// 切换仓储
//    /// </summary>
//    /// <typeparam name="TEntity">实体类型</typeparam>
//    /// <returns>仓储</returns>
//    public virtual SqlSugarCacheRepository<TEntity> Change<TEntity>()
//        where TEntity : class, new()
//    {
//        return _serviceProvider.GetService<SqlSugarCacheRepository<TEntity>>();
//    }
//}